import 'package:dali_ng_pera/page/certification/utils/dnp_image_compression_utils.dart';
import 'package:dali_ng_pera/page/widget/dnp_app_bar.dart';
import 'package:dali_ng_pera/tool/dnp_time_tool.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import '../../manager/dnp_plugin_manager.dart';
import '../../mob/dnp_mob.dart';
import '../../net/dnp_net_manager.dart';
import '../../plugin/dnp_plugin/lib/dnp_plugin.dart';
import '../widget/dnp_dotted_line_widget.dart';
import 'dialog/dnp_identity_correct_dialog.dart';
import 'dialog/dnp_identity_please_confirm_dialog.dart';
import 'enum/identity_enum.dart';
import 'model/dnp_identity_upload_model.dart';

class DnpIdentityInformationPage extends StatefulWidget {
  final List<String> attend;
  final List<String> begun;
  const DnpIdentityInformationPage({super.key, required this.attend,required this.begun});

  @override
  State<DnpIdentityInformationPage> createState() =>
      _DnpIdentityInformationPageState();
}

class _DnpIdentityInformationPageState
    extends State<DnpIdentityInformationPage> {
  String _curCircumstances = "";
  final idTypeQuarterTurns = 0.obs;
  final otherIdTypeQuarterTurns = 0.obs;
  final idTypeExpanded = true.obs;
  final otherIdTypeExpanded = true.obs;
  final frontUploadModel = DnpIdentityUploadModel().obs;
  int startTypeTime = 0;
  int endTypeTime = 0;
  int endUploadTime = 0;


  String get curCircumstances {
    if (_curCircumstances.isEmpty) {
      if (widget.attend.isNotEmpty) {
        _curCircumstances = widget.attend[0];
        return _curCircumstances;
      }
    }
    return _curCircumstances;
  }

  @override
  void initState() {
    super.initState();
    startTypeTime = DnpTimeTool.timestamp;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: "Product details"),
            Expanded(
              child: SingleChildScrollView(
                child: buildContent(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildContent() {
    return LayoutBuilder(
      builder: (context, constraints) {
        return ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: MediaQuery.of(context).size.height -
                MediaQuery.of(context).padding.top -
                60, // AppBar height (12 + 34 + 14)
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 14,
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 14),
                    child: Text(
                      "Select an ID to verify your identity",
                      style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 16,
                          color: Color(0xFF252630)),
                    ),
                  ),
                  _buildIdentityType(
                      "Recommended ID type",
                      widget.attend,
                      idTypeQuarterTurns,
                      idTypeExpanded),
                  _buildIdentityType(
                      "Other ID type",
                      widget.begun,
                      otherIdTypeQuarterTurns,
                      otherIdTypeExpanded),
                ],
              ),
              _buildButton(),
            ],
          ),
        );
      },
    );
  }

  Widget _buildIdentityType(String title, List<String> options,
      Rx<int> quarterTurns, Rx<bool> expanded) {
    return Container(
      margin: EdgeInsets.only(left: 14, right: 14, top: 15),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if (quarterTurns.value == 0) {
                quarterTurns.value = 90;
              } else {
                quarterTurns.value = 0;
              }
              expanded.value = !expanded.value;
            },
            child: Obx(() => AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                  height: 53,
                  decoration: BoxDecoration(
                    color: Color(0xFF1D4AC8),
                    borderRadius: expanded.value
                        ? BorderRadius.only(
                            topRight: Radius.circular(19),
                            topLeft: Radius.circular(19))
                        : BorderRadius.circular(19),
                  ),
                  child: Row(
                    children: [
                      SizedBox(
                        width: 13,
                      ),
                      Text(
                        title,
                        style: TextStyle(
                            fontSize: 16,
                            color: Colors.white,
                            fontWeight: FontWeight.w700),
                      ),
                      Spacer(),
                      Obx(() => RotatedBox(
                            quarterTurns: quarterTurns.value,
                            child: Image.asset(
                              "assets/images/ic_certification_down_up_arrow.png",
                              width: 18,
                              height: 10,
                            ),
                          )),
                      SizedBox(
                        width: 13,
                      ),
                    ],
                  ),
                )),
          ),
          Obx(() => AnimatedSize(
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
                child: expanded.value
                    ? Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(
                              color: Color(0xFF1D4AC8),
                              width: 1,
                              style: BorderStyle.solid),
                          borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(19),
                              bottomLeft: Radius.circular(19)),
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: options.map((e) {
                            return GestureDetector(
                              behavior: HitTestBehavior.translucent,
                              onTap: () {
                                setState(() {
                                  _curCircumstances = e;
                                });
                              },
                              child: Column(
                                children: [
                                  const SizedBox(
                                    height: 14,
                                  ),
                                  Row(
                                    children: [
                                      SizedBox(
                                        width: 14,
                                      ),
                                      Text(
                                        e,
                                        style: TextStyle(
                                            color: Color(0xFF333333),
                                            fontSize: 15,
                                            fontWeight: FontWeight.w500),
                                      ),
                                      Spacer(),
                                      Image.asset(
                                        e == curCircumstances
                                            ? "assets/images/ic_certification_select_circle.png"
                                            : "assets/images/ic_certification_no_select_circle.png",
                                        width: 16,
                                        height: 16,
                                      ),
                                      SizedBox(
                                        width: 14,
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 14,
                                  ),
                                  if (e != options.last)
                                    DnpHorizontalDottedLineWidget(
                                      width: double.infinity,
                                      height: 1,
                                      color: Color(0xFFE4E4E4),
                                      marginLeft: 14,
                                      marginRight: 14,
                                    ),
                                ],
                              ),
                            );
                          }).toList(),
                        ),
                      )
                    : SizedBox.shrink(),
              )),
        ],
      ),
    );
  }

  Widget _buildButton() {
    return GestureDetector(
      onTap: () {
        endTypeTime = DnpTimeTool.timestamp;
        DnpMob.inexplicable("2", startTypeTime, endTypeTime);
        showDialog(
            context: context,
            builder: (context) {
              return DnpIdentityCorrectDialog(
                identityType: IdentityType.FrontOfIDPhoto,
                onNext: () async {
                  Map<dynamic, dynamic>? result = await DnpPlugin().showActionSheet;
                  onUploadImage(
                      result?["imageBytes"] ?? [],
                      result?["isCameraOpen"] ?? false,
                      11,
                      curCircumstances,
                      callback: onUploadImageCallBack);
                },
              );
            });
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: double.infinity,
        height: 48,
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 24, right: 24, top: 14, bottom: 34),
        decoration: BoxDecoration(
            color: Color(0xFF1D4AC8), borderRadius: BorderRadius.circular(10)),
        child: Text("Get a loan",
            style: TextStyle(
                fontSize: 16,
                color: Colors.white,
                fontWeight: FontWeight.w600)),
      ),
    );
  }

  void onUploadImage(
      List<int>? bytes, bool isCameraOpen, int heard, String circumstances,
      {VoidCallback? callback}) async {
    ///"also":	int	否	图片来源:1拍照 2:相册选择
    /// "heard":	int	否	图片类型: 10:人像,11身份证正面
    /// "turnedIn"	File	否	图片文件
    /// "circumstances":	string	否	type=11时，证件类型： UMID/SSS/TIN/PASSPORT 等
    if (bytes == null) {
      return;
    }
    DnpPluginManager().showLoading();
    bytes = await DnpDecompressionUtils.compressImage(bytes);
    DnpNetManager()
        .uploadImage("/haseye/hemeis", imageBytes: bytes, queryParameters: {
      "also": isCameraOpen ? 1 : 2,
      "heard": heard,
      "circumstances": circumstances,
    }).then((value) {
      DnpPluginManager().hideLoading();
      if (value.success && value.iesous == "0") {
        try {
          frontUploadModel.value =
              DnpIdentityUploadModel.fromJson(value.close);
          callback?.call();
        } catch (e) {
          DnpPluginManager().showToast(e.toString());
        }
      } else {
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }

  void onUploadImageCallBack() {
    showDialog(
        context: context,
        builder: (context) {
          return DnpIdentityPleaseConfirmDialog(
            model: frontUploadModel.value,
            onConfirm: () {
              onSubmit(frontUploadModel.value, "11",
                  callback: () {
                    Get.back();
                    DnpMob.inexplicable("3", endTypeTime, DnpTimeTool.timestamp);
                    Get.back<String>(result: curCircumstances);
                  });
            },
          );
        });
  }

  void onSubmit(DnpIdentityUploadModel model,String heard,{VoidCallback? callback}) {
    DnpPluginManager().showLoading();
    DnpNetManager().post("/haseye/kai",
        data: dio.FormData.fromMap({
          "st":
          "${model.ceremonial}-${model.worshipper?.padLeft(2, "0")}-${model.business?.padLeft(2, "0")}",
          "suburb": model.random,
          "beersheba": model.beersheba,
          "heard": heard,
          "circumstances": curCircumstances
        })).then((value){
      DnpPluginManager().hideLoading();
      if(value.success && value.iesous == "0"){
        callback?.call();
      }else{
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }
}
